package com.qf.controller;

import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.utils.CodeUtils;
import com.qf.utils.TokenUtils;
import com.qf.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {


    public static final String USER_PRE = "userinfo:";

    // 常用的依赖注入的方式，使用 @Autowired 即可
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @GetMapping("/codelogin")
    public ResultVo codeLogin(String phone,String code){

        //1. 从redis中获取该手机号对应的验证码
        String prefix = "sendcode:";
        String key = prefix+phone;

        String cacheCode = (String) redisTemplate.opsForValue()
                .get(key);

        if (cacheCode==null){
            return new ResultVo(-1,"验证码过期了",null);
        }

        if (cacheCode.equals(code)){

            // 根据手机号查询用户信息
            User user = userService.findUserByPhone(phone);



            // 把用户信息写入 Redis中 ，便于后面的其他接口查询用户信息
            String uuid = UUID.randomUUID().toString();
            String userKey = USER_PRE+uuid;

            redisTemplate.opsForValue()
                    .set(userKey,user);

            // 创建jwt
            String token = TokenUtils.createToken(uuid,user.getUsername(), 120);

            HashMap<String, Object> data = new HashMap<>();
            data.put("token",token);
            data.put("user",user);

            // 返回jwt token
            return new ResultVo(1,"登录成功",data);
        }else {
            return new ResultVo(-1,"验证码输入错误",null);
        }

    }

    @GetMapping("/sendcode")
    public ResultVo sendCode(String phone){

        //1. 生成一个长度为6的验证码
        String code = CodeUtils.createCode(6);

        //2. 把验证码存放到redis中
        String prefix = "sendcode:";
        String key = prefix+phone;

        redisTemplate.opsForValue().set(key,code,60, TimeUnit.SECONDS);
        //3. 调用阿里云的短信接口发送验证码到手机
        System.out.println(code);

        //4. 返回json
        return new ResultVo(1,"ok",null);
    }

}
